package com.java.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class TcpServer {
	private ServerSocket ss;
	private int count=0;
	private Socket s;

	public TcpServer() {
		try {
			ss = new ServerSocket(8888);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void startService() {
		while (true) {
			try {
				s = ss.accept();//不停地等电话，等到一个电话就创建一个线程
				new serverThread(s).start();
				this.count++;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}		
	}

	private class serverThread extends Thread {
		private Socket s;
		private Date date;
		public serverThread(Socket s) {
			this.s = s;
			date=new Date();
		}

		public void run() {
			BufferedReader br = null;
			PrintWriter pw = null;
			try {
				br = new BufferedReader(new InputStreamReader(s
						.getInputStream()));
				String str = br.readLine();
				System.out.println("第"+count+"人访："+str+"\t"+date);
				str = str.toUpperCase();
				pw = new PrintWriter(s.getOutputStream());
				pw.println(str);
				pw.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		new TcpServer().startService();
	}
}
